package com.eian.boot.rabbit.aspect;

import com.eian.boot.rabbit.RabbitHelper;
import com.eian.boot.rabbit.model.Message;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Aspect
@Component
@ConditionalOnBean(RabbitHelper.class)
public class MessageWrapperAspect {

    private final Environment environment;

    public MessageWrapperAspect(Environment environment) {
        this.environment = environment;
    }

    @Around("execution(* com.eian.boot.rabbit.RabbitHelper.send(..)) && args(exchange, routingKey, payload)")
    public Object wrapMessage(ProceedingJoinPoint joinPoint,
                              String exchange,
                              String routingKey,
                              Object payload) throws Throwable {

        // 已经是统一消息类型，直接传递
        if (payload instanceof Message<?>) {
            return joinPoint.proceed(new Object[]{exchange, routingKey, payload});
        }

        // 从环境变量获取应用名称作为消息来源
        String appName = environment.getProperty("spring.application.name", "unknown-service");

        // 创建统一消息结构
        var unifiedMessage = new Message<>(payload)
                .withSource(appName);

        // 使用新消息参数继续执行
        return joinPoint.proceed(new Object[]{exchange, routingKey, unifiedMessage});
    }
}